<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="65%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="160"
    >
      <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
      <div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="送货单号">
              <span>{{ formData.deliveryCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工厂" prop="plantId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.plantId"
                placeholder="请选择工厂"
                clearable
                @change="changePlant"
              >
                <el-option
                  v-for="item in plantList"
                  :key="item.id"
                  :label="item.organizationCode"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.plantCode }}</span>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="工厂编码" prop="plantCode">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.plantCode" placeholder="请输入工厂编码" clearable/>-->
          <!--              <span v-else>{{ formData.plantCode }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="工厂名称" prop="plantName">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.plantName" placeholder="请输入工厂名称" clearable/>-->
          <!--              <span v-else>{{ formData.plantName }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="送货类型" prop="exteriorDeliveryType">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.exteriorDeliveryType"
                placeholder="请选择送货类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList(
                    'DeliveryOrderType'
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{
                dictionaryStore.filterDictName(
                  "DeliveryOrderType",
                  formData.exteriorDeliveryType
                )
              }}</span>
            </el-form-item>
          </el-col>

          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="公司" prop="organizationId">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.organizationId" placeholder="请输入公司"-->
          <!--                        clearable/>-->
          <!--              <span v-else>{{ formData.organizationId }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="公司代码" prop="organizationCode">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.organizationCode"-->
          <!--                        placeholder="请输入公司代码" clearable/>-->
          <!--              <span v-else>{{ formData.organizationCode }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="公司名称" prop="organizationName">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.organizationName"-->
          <!--                        placeholder="请输入公司名称" clearable/>-->
          <!--              <span v-else>{{ formData.organizationName }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="交货地点" prop="storageLocationId">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.storageLocationId"-->
          <!--                        placeholder="请输入交货地点" clearable/>-->
          <!--              <span v-else>{{ formData.storageLocationId }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="交货地点编号" prop="storageLocationCode">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.storageLocationCode"-->
          <!--                        placeholder="请输入交货地点编号" clearable/>-->
          <!--              <span v-else>{{ formData.storageLocationCode }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="交货地点名称" prop="storageLocationName">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.storageLocationName"-->
          <!--                        placeholder="请输入交货地点名称" clearable/>-->
          <!--              <span v-else>{{ formData.storageLocationName }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="预计到货日期" prop="expectedDeliveryDate">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.expectedDeliveryDate"-->
          <!--                        placeholder="请输入预计到货日期" clearable/>-->
          <!--              <span v-else>{{ formData.expectedDeliveryDate }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="到货时间窗开始时间" prop="arriveTimeWindowBegin">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.arriveTimeWindowBegin"-->
          <!--                        placeholder="请输入到货时间窗开始时间" clearable/>-->
          <!--              <span v-else>{{ formData.arriveTimeWindowBegin }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="到货时间窗结束时间" prop="arriveTimeWindowEnd">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.arriveTimeWindowEnd"-->
          <!--                        placeholder="请输入到货时间窗结束时间" clearable/>-->
          <!--              <span v-else>{{ formData.arriveTimeWindowEnd }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="到货时间窗编号" prop="arriveTimeWindowCode">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.arriveTimeWindowCode"-->
          <!--                        placeholder="请输入到货时间窗编号" clearable/>-->
          <!--              <span v-else>{{ formData.arriveTimeWindowCode }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="承运商" prop="generalCarrierId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.generalCarrierId"
                value-key="id"
                :disabled="formData.plantId === ''"
                placeholder="请选择承运商"
                clearable
                @change="changeGeneralCarrier"
              >
                <el-option
                  v-for="item in generalCarrierList"
                  :key="item.id"
                  :label="item.generalCarrierCode"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.generalCarrierCode }}</span>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="发货联系人" prop="shippingContactPerson">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.shippingContactPerson"-->
          <!--                        placeholder="请输入发货联系人" clearable/>-->
          <!--              <span v-else>{{ formData.shippingContactPerson }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="发货联系人电话" prop="shippingContactPhone">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.shippingContactPhone"-->
          <!--                        placeholder="请输入发货联系人电话" clearable/>-->
          <!--              <span v-else>{{ formData.shippingContactPhone }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="车牌号" prop="vehicleCode">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.vehicleCode" placeholder="请输入车牌号" clearable/>-->
          <!--              <span v-else>{{ formData.vehicleCode }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="车牌号" prop="vehicleCode">
              <el-select
                v-if="!props.isReadonly"
                :disabled="formData.generalCarrierId === ''"
                v-model="formData.vehicleCode"
                value-key="id"
                placeholder="请选择车牌号"
                @change="changeVehicle"
                clearable
              >
                <el-option
                  v-for="item in carrierVehicleList"
                  :key="item.id"
                  :label="item.vehicleCode"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.vehicleCode }}</span>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="车辆类型id" prop="vehicleTypeId">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.vehicleTypeId" placeholder="请输入车辆类型id"-->
          <!--                        clearable/>-->
          <!--              <span v-else>{{ formData.vehicleTypeId }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="车辆类型编号" prop="vehicleTypeCode">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.vehicleTypeCode" placeholder="请输入车辆类型编号"-->
          <!--                        clearable/>-->
          <!--              <span v-else>{{ formData.vehicleTypeCode }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="车型" prop="vehicleTypeName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.vehicleTypeName"
                placeholder="请输入车型"
                clearable
              />
              <span v-else>{{ formData.vehicleTypeName }}</span>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="车辆行驶证号" prop="vehicleRegistration">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.vehicleRegistration"-->
          <!--                        placeholder="请输入车辆行驶证号" clearable/>-->
          <!--              <span v-else>{{ formData.vehicleRegistration }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="司机" prop="driverName">
              <el-select
                v-if="!props.isReadonly"
                :disabled="formData.generalCarrierId === ''"
                v-model="formData.driverName"
                value-key="id"
                placeholder="请选择司机"
                @change="changeDriver"
                clearable
              >
                <el-option
                  v-for="item in carrierDriverList"
                  :key="item.id"
                  :label="item.driverName"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.driverName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="driverPhone">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.driverPhone"
                :disabled="formData.driverName === ''"
                placeholder="请输入交货地"
                clearable
                maxlength="25"
              />
              <span v-else>{{ formData.driverPhone }}</span>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="司机驾驶证号" prop="driverRegistration">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.driverRegistration"-->
          <!--                        placeholder="请输入司机驾驶证号" clearable/>-->
          <!--              <span v-else>{{ formData.driverRegistration }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="发货状态" prop="shipmentStatus">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.shipmentStatus" placeholder="请输入发货状态"-->
          <!--                        clearable/>-->
          <!--              <span v-else>{{ formData.shipmentStatus }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="收货状态" prop="receiveStatus">-->
          <!--              <el-input v-if="!props.isReadonly" v-model="formData.receiveStatus" placeholder="请输入收货状态"-->
          <!--                        clearable/>-->
          <!--              <span v-else>{{ formData.receiveStatus }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
      </div>
      <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
      <el-card shadow="never" class="table-container">
        <!--          <el-tabs v-model="defaultTabValue" type="border-card">-->
        <!--            <el-tab-pane label="联系人" :name="1"></el-tab-pane>-->
        <!--            <el-tab-pane label="联系人" :name="2"></el-tab-pane>-->
        <!--          </el-tabs>-->
        <template #header v-if="!props.isReadonly">
          <el-button type="success" plain @click="addinfo()">
            <i-ep-plus />
            新增
          </el-button>
        </template>
        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <!--            <el-table-column label="物料" props="materialId" min-width="150">-->
            <!--              <template #default="{$index,row}">-->
            <!--                <el-form-item :prop="'details.' + $index + '.materialId'" :rules="rules.sonmaterialId"-->
            <!--                              label-width="0">-->
            <!--                  <el-input v-if="!props.isReadonly" v-model="row.materialId" placeholder="请输入物料id" clearable/>-->
            <!--                  <span v-else>{{ row.materialId }}</span>-->
            <!--                </el-form-item>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column
              label="存货编码"
              props="materialCode"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.materialCode'"
                  :rules="rules.sonmaterialCode"
                  label-width="0"
                >
                  <span>{{ row.materialCode }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="批次号" props="stockBatch" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.stockBatch'"
                  :rules="rules.sonstockBatch"
                  label-width="0"
                >
                  <span>{{ row.stockBatch }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              label="容量"
              props="materialQuantity"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.materialQuantity'"
                  :rules="rules.sonmaterialQuantity"
                  label-width="0"
                >
                  <el-input-number
                    v-if="!props.isReadonly"
                    v-model="row.materialQuantity"
                    style="width: 100px"
                    controls-position="right"
                    :min="0"
                  />
                  <span v-else>{{ row.materialQuantity }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="包装数量"
              props="quantityUnit"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.quantityUnit'"
                  :rules="rules.sonquantityUnit"
                  label-width="0"
                >
                  <el-input-number
                    v-if="!props.isReadonly"
                    v-model="row.quantityUnit"
                    style="width: 100px"
                    controls-position="right"
                    :min="0"
                  />
                  <span v-else>{{ row.quantityUnit }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="供应批次"
              props="supplyBatch"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.supplyBatch'"
                  :rules="rules.sonsupplyBatch"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.supplyBatch"
                    placeholder="请输入供应批次"
                    clearable
                  />
                  <span v-else>{{ row.supplyBatch }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" props="remarks" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.remarks'"
                  :rules="rules.sonremarks"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.remarks"
                    placeholder="请输入备注"
                    clearable
                  />
                  <span v-else>{{ row.remarks }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="300"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialogRecord"
    title="外协订单信息"
    width="80%"
    draggable
    @close="closeDialogRecord"
    :key="addKey"
  >
    <div class="search-container">
      <el-form ref="tableFormRef" :inline="true">
        <!--        <el-form-item label="工厂">-->
        <!--          <el-select-->
        <!--              v-model="searchParam.plantId"-->
        <!--              placeholder="请选择工厂"-->
        <!--              clearable-->
        <!--          >-->
        <!--            <el-option-->
        <!--                v-for="item in plantList"-->
        <!--                :key="item.id"-->
        <!--                :label="item.organizationCode"-->
        <!--                :value="item.id"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="物料">
          <el-select
            v-model="searchParam.materialId"
            placeholder="请选择工厂"
            clearable
          >
            <el-option
              v-for="item in productData"
              :key="item.materialId"
              :label="item.materialCode"
              :value="item.materialId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="批次号">
          <el-input
            v-model="searchParam.materialBatch"
            placeholder="请输入批次号"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getListForSrm">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <div class="formTable">
        <el-table
          :data="mesexteriorrecordList"
          style="width: 100%"
          :key="Math.random"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="物料" prop="materialCode" min-width="150" />
          <el-table-column label="批次" prop="materialBatch" min-width="150" />
          <el-table-column
            label="接收数量"
            prop="materialQuantity"
            min-width="150"
          />
          <el-table-column
            label="完成数量"
            prop="finishQuantity"
            min-width="150"
          />
          <el-table-column
            label="返回数量"
            prop="returnQuantity"
            min-width="150"
          />
        </el-table>
      </div>
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleRecord"
          >确 定
        </el-button>
        <el-button @click="closeDialogRecord">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { iteratee } from "lodash"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PARTNERSRMEXTERIORDELIVERYADDORUPDATE",
  inheritAttrs: false,
});
const defaultTabValue = ref(1);

const init = (id?: any) => {
  getPlantList();
  getGeneralCarrierList();
  if (id) {
    // getInfo(id);
    getdetails(id);
  } else {
    getCode();
  }
  visibleDialog.value = true;
};

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  deliveryCode: "",
  exteriorDeliveryType: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  supplierId: "",
  supplierCode: "",
  supplierName: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  expectedDeliveryDate: "",
  arriveTimeWindowBegin: "",
  arriveTimeWindowEnd: "",
  arriveTimeWindowCode: "",
  generalCarrierId: "",
  generalCarrierCode: "",
  shippingContactPerson: "",
  shippingContactPhone: "",
  vehicleCode: "",
  vehicleTypeId: "",
  vehicleTypeCode: "",
  vehicleTypeName: "",
  vehicleRegistration: "",
  driverName: "",
  driverPhone: "",
  driverRegistration: "",
  shipmentStatus: "",
  receiveStatus: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  details: [],
});

/** rules规则 */
const rules = reactive({
  deliveryCode: [
    { required: true, message: "请输入送货单号;自动生成", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  exteriorDeliveryType: [
    { required: true, message: "请选择送货类型", trigger: "blur" },
  ],
  organizationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  organizationCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  organizationName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantId: [
    { required: true, message: "请选择工厂", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  plantCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  supplierId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  supplierCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  supplierName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  storageLocationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  storageLocationCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  storageLocationName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  expectedDeliveryDate: [],
  arriveTimeWindowBegin: [],
  arriveTimeWindowEnd: [],
  arriveTimeWindowCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  generalCarrierId: [
    { message: "请选择承运商", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  generalCarrierCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  shippingContactPerson: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  shippingContactPhone: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  vehicleCode: [
    { message: "请选择车牌号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  vehicleTypeId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  vehicleTypeCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  vehicleTypeName: [
    { message: "请输入车型", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  vehicleRegistration: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  driverName: [
    { message: "请选择司机", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  driverPhone: [
    { message: "请输入联系电话", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  driverRegistration: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  shipmentStatus: [],
  receiveStatus: [],
  sonexteriorDeliveryId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonexteriorDeliveryCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonmaterialId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonmaterialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonstockBatch: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonsupplyBatch: [
    { required: true, message: "请输入供应批次", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonmaterialQuantity: [
    { required: true, message: "请输入容量", trigger: "blur" },
  ],
  sonquantityUnit: [
    { required: true, message: "请输入包裝数量", trigger: "blur" },
  ],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  exteriorDeliveryId: "",
  exteriorDeliveryCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  stockBatch: "",
  supplyBatch: "",
  materialQuantity: "",
  quantityUnit: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.deliveryCode = "";
  formData.exteriorDeliveryType = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.supplierId = "";
  formData.supplierCode = "";
  formData.supplierName = "";
  formData.storageLocationId = "";
  formData.storageLocationCode = "";
  formData.storageLocationName = "";
  formData.expectedDeliveryDate = "";
  formData.arriveTimeWindowBegin = "";
  formData.arriveTimeWindowEnd = "";
  formData.arriveTimeWindowCode = "";
  formData.generalCarrierId = "";
  formData.generalCarrierCode = "";
  formData.shippingContactPerson = "";
  formData.shippingContactPhone = "";
  formData.vehicleCode = "";
  formData.vehicleTypeId = "";
  formData.vehicleTypeCode = "";
  formData.vehicleTypeName = "";
  formData.vehicleRegistration = "";
  formData.driverName = "";
  formData.driverPhone = "";
  formData.driverRegistration = "";
  formData.shipmentStatus = "";
  formData.receiveStatus = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 外协送货单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/srm/srmexteriordelivery/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails(id: any) {
  let sondetails = await request({
    url: "/srm/srmexteriordelivery/getDetails",
    method: "post",
    data: { id: id },
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

/**
 * 获取未完成的列表
 * */

const mesexteriorrecordList = ref([]);

const addKey = ref(0);

function addinfo() {
  addKey.value++;
  getListForSrm();
  getMaterialsInfo();
  visibleDialogRecord.value = true;
  rocrdSelections.value = [];
}

async function getListForSrm() {
  let { data } = await request({
    url: "/mes/mesexteriorrecord/getListForSrm",
    method: "post",
    data: searchParam,
  }).finally(() => {
    loading.value = false;
  });
  let ids = formData.details.map((item) => item.materialId);
  let stockBatchs = formData.details.map((item) => item.stockBatch);
  mesexteriorrecordList.value = [];
  data.forEach((item) => {
    if (
      !(
        ids.includes(item.materialId) &&
        stockBatchs.includes(item.materialBatch)
      )
    ) {
      mesexteriorrecordList.value.push(item);
    }
  });
}

//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};

const changePlant = (id: any) => {
  formData.plantId = id;
  plantCode(id);
};

const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    formData.plantCode = data.organizationCode;
    formData.plantName = data.organizationName;
  }
};

const generalCarrierList: any = ref(); // 承运商
const carrierVehicleList: any = ref(); // 车辆
const carrierDriverList: any = ref(); // 司机

const getGeneralCarrierList = async () => {
  const { data } = await request({
    url: "/mdm/mdmgeneralcarrier/getGeneralCarrierList",
    method: "post",
    data: {
      enabled: 1,
    },
  });
  generalCarrierList.value = data;
};

const changeGeneralCarrier = async (id: any) => {
  formData.generalCarrierId = id;
  const genData = generalCarrierList.value.find((item: any) => item.id === id);
  formData.generalCarrierCode = genData.generalCarrierCode;
  formData.vehicleCode = "";
  formData.vehicleTypeId = "";
  formData.vehicleTypeCode = "";
  formData.vehicleTypeName = "";
  formData.vehicleRegistration = "";
  formData.driverName = "";
  formData.driverPhone = "";
  formData.driverRegistration = "";
  getVehicleList(id);
  getDriverList(id);
};

const getVehicleList = async (generalCarrierId: any) => {
  const { data } = await request({
    url: "/mdm/mdmgeneralcarrier/getVehicleList",
    method: "post",
    data: {
      generalCarrierId: generalCarrierId,
      enabled: 1,
    },
  });
  carrierVehicleList.value = data;
};

const changeVehicle = async (id: any) => {
  const carData = carrierVehicleList.value.find((item: any) => item.id === id);
  formData.vehicleCode = carData.vehicleCode;
  formData.vehicleTypeId = carData.vehicleTypeId;
  formData.vehicleTypeCode = carData.vehicleTypeCode;
  formData.vehicleTypeName = carData.vehicleTypeName;
  formData.vehicleRegistration = carData.vehicleRegistration;
};

const getDriverList = async (generalCarrierId: any) => {
  const { data } = await request({
    url: "/mdm/mdmgeneralcarrier/getDriverList",
    method: "post",
    data: {
      generalCarrierId: generalCarrierId,
      enabled: 1,
    },
  });
  carrierDriverList.value = data;
};

const changeDriver = async (id: any) => {
  const carData = carrierDriverList.value.find((item: any) => item.id === id);
  formData.driverName = carData.driverName;
  formData.driverPhone = carData.driverPhone;
  formData.driverRegistration = carData.driverRegistration;
};

defineExpose({
  init,
});

async function getInfo(id: string) {
  request({
    url: `/srm/srmexteriordelivery/get/${id}`,
    method: "get",
  })
    .then((data) => {
      formData = data.data;
    })
    .catch((res) => {
      console.log(res);
    });
}

async function getCode(id: string) {
  request({
    url: `/srm/srmexteriordelivery/getCode`,
    method: "post",
    data: {},
  })
    .then((data) => {
      formData.deliveryCode = data.data;
    })
    .catch((res) => {
      console.log(res);
    });
}

const visibleDialogRecord = ref(false);

/** 关闭表单弹窗 */
function closeDialogRecord() {
  visibleDialogRecord.value = false;
}

/** 确定按钮 */
function handleRecord() {
  visibleDialogRecord.value = false;
  rocrdSelections.value.forEach((itme) => {
    let addItemTable = JSON.parse(JSON.stringify(details));
    addItemTable.materialId = itme.materialId;
    addItemTable.materialCode = itme.materialCode;
    addItemTable.materialName = itme.materialName;
    addItemTable.stockBatch = itme.materialBatch;
    addItemTable.productionMaterialId = itme.productionMaterialId;
    addItemTable.productionMaterialCode = itme.productionMaterialCode;
    addItemTable.materialQuantity = 1;
    addItemTable.quantityUnit = 1;
    console.log(itme.productionMaterialId);
    formData.details.push(addItemTable);
  });
}

/** 关闭表单弹窗 */
const rocrdSelections = ref([]);

function handleSelectionChange(selection: any) {
  rocrdSelections.value = selection;
}

// 初始化搜索参数数据
const searchParam = reactive({
  plantId: "",
  materialId: "",
  materialBatch: "",
});

const productData = ref([]);

async function getMaterialsInfo() {
  request({
    url: `/mdm/partnerproduct/materials`,
    method: "post",
  })
    .then((data) => {
      productData.value = data.data;
    })
    .catch((res) => {
      console.log(res);
    });
}

const reset = () => {
  searchParam.plantId = "";
  searchParam.materialId = "";
  searchParam.materialBatch = "";
  getListForSrm();
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h1 {
    font-size: 16px;
  }
}

:deep(.el-form-item) {
  margin: 0;
  padding: 13px 0;
}
</style>
